const config = require("../../config/index")
const { localDate } = require("../../utils/index")
const MongoClient = require('mongodb').MongoClient;
const moment = require("moment")
class Mongo {
  static getIntance() {
    if (!Mongo.instance) {
      Mongo.instance = new Mongo()
    }
    return Mongo.instance
  }
  constructor() {
    this.connect()
    this.db;
  }
  add(collection, params) {
    return new Promise(async (resolve, reject) => {
      let db = await this.connect();
      console.log(Object.prototype.toString.call(db))
      if (Object.prototype.toString.call(db) === "[object Object]") {
        db.collection(collection).insertOne({ ...params, time: localDate() }, (err, res) => {
          if (err) {
            reject(err);
            return
          }
          resolve(res)
        })
      } else {
        reject(db)
      }
    })
  }
  remove(collection, rule = { "name": "null" }) {
    return new Promise(async (resolve, reject) => {
      let db = await this.connect();
      if (Object.prototype.toString.call(db) === "[object Object]") {
        db.collection(collection).deleteOne(rule, (err, res) => {
          if (err) {
            reject(err)
          } else {
            resolve(res)
          }
        })
      } else {
        reject(db)
      }
    })
  }
  find(collection, params = {}) {
    console.log(params)
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        // this.db = db
        db.collection(collection).find(params).limit(10).toArray((err, res) => {
          if (err) {
            reject(err);
            return
          }
          resolve(res)
        })
      }).catch(res => {
        reject(res)
        console.log(res)
      })
    })
  }
  update(collection, rule, params) {
    return new Promise(async (resolve, reject) => {
      let db = await this.connect();
      if (Object.prototype.toString.call(db) === "[object Object]") {
        db.collection(collection).updateOne(rule, { $set: params }, (err, res) => {
          if (err) {
            reject(err);
          } else {
            resolve(res)
          }
        })
      } else {
        reject(db)
      }

    })
  }
  connect() {

    return new Promise((resolve, reject) => {
      if (this.db) {
        resolve(this.db)
      } else {
        MongoClient.connect(config.url, { useUnifiedTopology: true }, (err, client) => {
          if (err) {
            reject(err)
            return
          }
          let db = client.db(config.dbName)
          resolve(db)
          this.db = db
        });
      }

    })
  }
}

const mongo = Mongo.getIntance();


module.exports = mongo;